"""
简单的Qt异步处理示例
"""

import asyncio
import threading
import time
from PySide6.QtWidgets import QApplication, QMainWindow, QLabel, QPushButton, QVBoxLayout, QWidget
from PySide6.QtCore import QObject, Signal, Slot, Qt


class AsyncWorker(QObject):
    """异步工作线程"""
    # 定义信号
    result_ready = Signal(str)  # 处理结果信号
    error_occurred = Signal(str)  # 错误信号
    
    def __init__(self):
        super().__init__()
        
    async def do_async_work(self, task_name: str):
        """执行异步工作"""
        try:
            # 模拟异步操作
            await asyncio.sleep(2)
            
            # 模拟可能的错误
            if "error" in task_name.lower():
                raise Exception(f"模拟错误: {task_name}")
            
            result = f"完成任务: {task_name}"
            # 发出结果信号
            self.result_ready.emit(result)
            
        except Exception as e:
            # 发出错误信号
            self.error_occurred.emit(str(e))


class MainWindow(QMainWindow):
    """主窗口"""
    
    def __init__(self):
        super().__init__()
        self.init_ui()
        self.setup_worker()
        
    def init_ui(self):
        """初始化UI"""
        self.setWindowTitle("简单异步处理示例")
        self.setGeometry(200, 200, 400, 200)
        
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        layout = QVBoxLayout(central_widget)
        
        self.status_label = QLabel("点击按钮开始异步任务")
        self.status_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        layout.addWidget(self.status_label)
        
        self.normal_button = QPushButton("正常异步任务")
        self.normal_button.clicked.connect(self.start_normal_task)
        layout.addWidget(self.normal_button)
        
        self.error_button = QPushButton("错误异步任务")
        self.error_button.clicked.connect(self.start_error_task)
        layout.addWidget(self.error_button)
        
    def setup_worker(self):
        """设置工作线程"""
        self.worker = AsyncWorker()
        
        # 连接信号槽
        self.worker.result_ready.connect(self.on_result_ready)
        self.worker.error_occurred.connect(self.on_error_occurred)
        
    @Slot()
    def start_normal_task(self):
        """开始正常任务"""
        self.status_label.setText("正在执行正常任务...")
        self.normal_button.setEnabled(False)
        self.error_button.setEnabled(False)
        
        # 在新线程中运行异步任务
        def run_task():
            asyncio.run(self.worker.do_async_work("正常任务"))
            
        thread = threading.Thread(target=run_task, daemon=True)
        thread.start()
        
    @Slot()
    def start_error_task(self):
        """开始错误任务"""
        self.status_label.setText("正在执行错误任务...")
        self.normal_button.setEnabled(False)
        self.error_button.setEnabled(False)
        
        # 在新线程中运行异步任务
        def run_task():
            asyncio.run(self.worker.do_async_work("error_task"))
            
        thread = threading.Thread(target=run_task, daemon=True)
        thread.start()
        
    @Slot(str)
    def on_result_ready(self, result: str):
        """处理结果就绪"""
        self.status_label.setText(result)
        self.normal_button.setEnabled(True)
        self.error_button.setEnabled(True)
        
    @Slot(str)
    def on_error_occurred(self, error_message: str):
        """处理错误发生"""
        self.status_label.setText(f"错误: {error_message}")
        self.normal_button.setEnabled(True)
        self.error_button.setEnabled(True)


def main():
    """主函数"""
    import sys
    app = QApplication(sys.argv)
    
    window = MainWindow()
    window.show()
    
    sys.exit(app.exec())


if __name__ == "__main__":
    main()